const db = require('../db/index')

// 导入配置文件
const config = require('../config')

// 解析 token 的中间件
const jwt = require('jsonwebtoken')

//获取用户的个人收藏
exports.getStoreup = (req, res) => {
    const sql = 'select status from storeup where refid = ? and userid = ?'
    db.query(sql, [req.params.refid, req.user.id], (err, results) => {
        // 执行 SQL 语句失败
        if (err) return res.cc(err.message)
        res.send({
            status: 200,
            message: '成功',
            data: results.length != 1 ? 0 : results[0].status
        })
    })
}

//是否取消收藏
exports.updateStoreup = (req, res) => {
    const sql = 'select count(*) as total from storeup where refid = ? and userid = ?'
    db.query(sql, [req.body.refid, req.user.id], (err, results) => {
        let status = req.body.status == 0 ? 1 : 0
            // 执行 SQL 语句失败
        if (err) {
            return res.cc(err.message)
        }
        if (results[0].total != 1) {
            const sql = 'insert into storeup set ?'
            db.query(sql, { refid: req.body.refid, userid: req.user.id, status: 1 }, (err, results) => {
                // 执行 SQL 语句失败
                if (err) {
                    return res.cc(err.message)
                }
                res.send({
                    status: 200,
                    message: '成功'
                })
            })
        } else {
            const sql = 'update storeup set status = ? where refid = ? and userid = ?'
            db.query(sql, [status, req.body.refid, req.user.id], (err, results) => {
                // 执行 SQL 语句失败
                if (err) {
                    return res.cc(err.message)
                }
                res.send({
                    status: 200,
                    message: '成功'
                })
            })
        }
    })

}

//获取电影是否被该用户收藏
exports.getStoreupAll = (req, res) => {
    const sql = `select refid from storeup where userid = ${req.user.id} and status = 1`
    db.query(sql, (err, results) => {
        if (err) return res.cc(err.message)
        let arr = []
        for (var i in results) {
            let a = Object.values(results[i])
            arr.push(a[0])
        }
        let h = ''
        for (let index = 1; index < arr.length; index++) {
            h += '?,'
            if ((index + 1) == arr.length) {
                h += '?'
            }
        }
        h = arr.length == 1 ? '?' : h
        if (h === '') {
            return res.send({
                status: 200,
                message: "获取成功",
                data: results
            })
        } else {
            const sql = `select * from movieinfo where id in (${h})`
            db.query(sql, arr, (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 200,
                    message: "获取成功",
                    data: results
                })
            })
        }
    })
}